package com.modelscope.ai.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.modelscope.ai.domain.dto.UserDto;
import com.modelscope.ai.domain.dto.UserLoginDto;
import com.modelscope.ai.domain.dto.UserQueryCriteria;
import com.modelscope.ai.domain.dto.WechatDto;
import com.modelscope.ai.domain.entity.R;
import com.modelscope.ai.domain.vo.ChatResult;
import com.modelscope.ai.domain.vo.OpenIdVo;
import com.modelscope.ai.domain.vo.UserVo;
import com.modelscope.ai.domain.vo.WeChatVo;
import com.modelscope.ai.service.UserService;
import com.modelscope.ai.service.WeChatService;
import com.modelscope.ai.utils.AssertUtil;
import com.modelscope.ai.utils.RequestHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RequiredArgsConstructor
@Slf4j
@Validated
@RestController
@RequestMapping("/login")
@Tag(name = "login", description = "用户登录")
public class LoginController {


    private final UserService userService;

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @PostMapping
    public R<String> login(@Valid @RequestBody UserLoginDto dto) {
        log.info("登录信息 -->{}", dto);
        return R.ok(userService.login(dto));
    }

    /**
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "注册用户信息")
    public R<String> register(@Valid @RequestBody UserDto userDto) {
        log.info("注册信息 -->{}", userDto);
        userService.register(userDto);
        return R.ok("注册成功");
    }

    final WeChatService weChatService;

    @PostMapping("/wechat")
    @Operation(summary = "微信注册")
    public R<OpenIdVo> register(@RequestBody WechatDto wechatDto) {
//        AssertUtil.isNotEmpty(wechatDto.(), "openid不存在");
        log.info("微信登录->{}", wechatDto);
        // 第一步，获取openid
        String json = weChatService.getOpenId("wx0925bacbc45d9603",
                "f78acc82fe1d3ee672862b4729f3f1a7",
                wechatDto.getCode(),
                "authorization_code"
        );
        ObjectMapper objectMapper = new ObjectMapper();
        ChatResult chatResult = null;
        WeChatVo openId=null;
        try {
            openId = objectMapper.readValue(json, WeChatVo.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("登录返回结果:{}",openId);
        AssertUtil.isNotEmpty(openId, "");
        AssertUtil.isTrue(openId.getOpenid().length() == "o2aEU5LoCaxd7A5_nHLfmUD4BY-I".length(), "openid不正确");
        return R.ok(userService.openid(openId.getOpenid()));
    }

}
